package com.pinyoumei.app.activity.ShoppingCenter;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.pinyoumei.app.R;
import com.pinyoumei.app.activity.BaseActivity;
import com.pinyoumei.app.bean.TipBean;
import com.pinyoumei.app.network.Constants;
import com.pinyoumei.app.view.FlowLayout;
import com.lzy.okgo.cache.CacheEntity;
import com.lzy.okgo.db.CacheManager;

import java.util.ArrayList;




/**
 * Created by Administrator on 2020-12-08.
 * --------- 日期 ------- 维护人 ------------ 变更内容 --------
 * 2020-12-08        Administrator             新增Person类
 * 2020-12-08        Administrator             增加sex属性
 * 搜索
 */
public class ShopSearchActivity extends BaseActivity implements View.OnClickListener {

   
    private EditText etSearch;
    private TabLayout tabPosTab;
//    private ShopSearchHisAdapter shopSearchListAdapter;

    private String CACHE = "search_list";
    private FlowLayout mFlowLayout;
    private RelativeLayout rl_history;
    private String[] titles;
    private String[] hot_list = {"洗衣液",  "纸巾", "休闲零食","体重秤","避孕套","衣架","儿童口罩","唇膏","挡风被","猫粮"};
    private int  titles_position = 0;
    private FlowLayout fl_search_list;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop_search);
        initWidget();
        InitData();
    }

    private void initWidget() {

        switch (Constants.BIND_PDD) {
        	case 0:
                titles = new String[]{"拼优美","淘宝",  "京东", "唯品会"};

        		break;

        	case 1:
                titles = new String[]{"拼优美","淘宝", "拼多多", "京东", "唯品会"};
        		break;

        	default:
        		break;
        }

        fl_search_list = findViewById(R.id.fl_search_list);
        hotListData();

        rl_history = findViewById(R.id.rl_history);
        RelativeLayout relativeFinish = findViewById(R.id.relative_finish);
        relativeFinish.setOnClickListener(this);

        LinearLayout ll_clean = findViewById(R.id.ll_clean);
        ll_clean.setOnClickListener(this);
        Button bt_search = findViewById(R.id.bt_search);
        bt_search.setOnClickListener(this);
        etSearch = findViewById(R.id.et_search);
        tabPosTab = findViewById(R.id.tab_pos_tab);
        tabPosTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                titles_position = tab.getPosition();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });

//        // 新建一个可以添加属性的文本对象
//        SpannableString ss = new SpannableString("在此粘贴标签，搜查隐藏优惠券拿返利");
//        ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.parseColor("#FF2F5C"));
//        ss.setSpan(foregroundColorSpan, 7, 14, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
//        // 设置hint
//        etSearch.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
//

        etSearch.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    search_text();
                    return true;
                }

                return false;
            }
        });


        mFlowLayout = findViewById(R.id.flowlayout);


        CacheEntity<ArrayList<TipBean>> search_list = (CacheEntity<ArrayList<TipBean>>) CacheManager.getInstance().get(CACHE);
        if (search_list != null && search_list.getData()!=null) {
            historyData(search_list.getData());
            rl_history.setVisibility(View.VISIBLE);
        } else {
            rl_history.setVisibility(View.GONE);
        }

    }



    private void hotListData() {
        fl_search_list.removeAllViews();
        for (int i = 0; i < hot_list.length; i++) {
            TextView tv = (TextView) LayoutInflater.from(ShopSearchActivity.this).inflate(
                    R.layout.item_shop_history, fl_search_list, false);
            tv.setText(hot_list[i]);
            final String str = tv.getText().toString();
            //点击事件
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //加入搜索历史纪录记录
                    Intent intent = new Intent(ShopSearchActivity.this,ShopSearchListActivity.class);
                    intent.putExtra("titles_position",titles_position);
                    intent.putExtra("query_name",str);
                    startActivity(intent);
                }
            });
            fl_search_list.addView(tv);
        }
    }

    private void historyData(ArrayList<TipBean> datas) {
        mFlowLayout.removeAllViews();
        for (int i = 0; i < datas.size(); i++) {
            TextView tv = (TextView) LayoutInflater.from(ShopSearchActivity.this).inflate(
                    R.layout.item_shop_history, mFlowLayout, false);
            tv.setText(datas.get(i).getTip());
            final String str = tv.getText().toString();
            //点击事件
            tv.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //加入搜索历史纪录记录
                    Intent intent = new Intent(ShopSearchActivity.this,ShopSearchListActivity.class);
                    intent.putExtra("titles_position",titles_position);
                    intent.putExtra("query_name",str);
                    startActivity(intent);
                }
            });
            mFlowLayout.addView(tv);
        }
    }

    private void search_text() {
        //搜索
        //点击搜索的时候隐藏软键盘
        InputMethodManager imm = (InputMethodManager) etSearch.getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(etSearch.getWindowToken(),0);
        }
        // 在这里写搜索的操作,一般都是网络请求数据
        String query_name = etSearch.getText().toString().trim();
        if (!TextUtils.isEmpty(query_name)) {
            TipBean tipBean = new TipBean();
            tipBean.setTip(query_name);


            CacheEntity<ArrayList<TipBean>> search_list = (CacheEntity<ArrayList<TipBean>>) CacheManager.getInstance().get(CACHE);
            //有缓存存入 无缓存创建
            if (search_list != null &&  search_list.getData()!=null) {
                search_list.getData().add(tipBean);
                CacheManager.getInstance().replace(CACHE, search_list);
                historyData(search_list.getData());
            } else {
                CacheEntity<ArrayList<TipBean>> tipBeanCacheEntity = new CacheEntity<>();
                ArrayList<TipBean> tipBeans = new ArrayList<>();
                tipBeans.add(tipBean);
                tipBeanCacheEntity.setData(tipBeans);
                CacheManager.getInstance().replace(CACHE, tipBeanCacheEntity);

                historyData(tipBeans);

                rl_history.setVisibility(View.VISIBLE);


            }

            Intent intent = new Intent(ShopSearchActivity.this,ShopSearchListActivity.class);
            intent.putExtra("titles_position",titles_position);
            intent.putExtra("query_name",query_name);
            startActivity(intent);
        } else {
            Toast.makeText(ShopSearchActivity.this, "请输入关键字搜索", Toast.LENGTH_SHORT).show();
        }
    }

    private void InitData() {
        for (int i = 0; i < titles.length; i++) {
            tabPosTab.addTab(tabPosTab.newTab().setText(titles[i]));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.relative_finish:
                finish();
                break;
            case R.id.bt_search:
                //搜索
                //点击搜索的时候隐藏软键盘
                search_text();
                break;

            case R.id.ll_clean:
                //清空
                CacheManager.getInstance().remove(CACHE);
                mFlowLayout.removeAllViews();
                break;

            default:
                break;
        }
    }
}
